package cn.usian.jyzx.user.controller;

import cn.hutool.core.util.RandomUtil;
import cn.usian.jyzx.common.util.SmsUtil;
import cn.usian.jyzx.model.dto.UserLoginDto;
import cn.usian.jyzx.model.dto.UserRegisterDto;
import cn.usian.jyzx.model.entity.user.UserAddress;
import cn.usian.jyzx.model.entity.user.UserInfo;
import cn.usian.jyzx.model.vo.common.Result;
import cn.usian.jyzx.model.vo.common.ResultCodeEnum;
import cn.usian.jyzx.user.service.UserAddressService;
import cn.usian.jyzx.user.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @TODO:
 * @Author:baimu
 * @Date:2024 11 04 14 59
 **/

@RestController
@Slf4j
public class UserController {

    @Autowired
    UserService userService;




    @GetMapping("/api/user/sms/sendCode/{phone}")
    public Result sendCode(@PathVariable String phone) throws Exception {

        log.info("手机号：{}",phone);
        userService.sendCode(phone);
        return Result.build(phone, ResultCodeEnum.SUCCESS);

    }

    ///api/user/userInfo/register


    @PostMapping("/api/user/userInfo/register")
    public Result register(@RequestBody UserRegisterDto userRegisterDto){
log.info("userRegisterDto:{}",userRegisterDto.toString());
        userService.register(userRegisterDto);
        return Result.build(null,ResultCodeEnum.SUCCESS);
    }




    @PostMapping("/api/user/userInfo/login")
    public Result login(@RequestBody UserLoginDto userLoginDto){
        log.info("userLoginDto:{}",userLoginDto.toString());
        String token = userService.login(userLoginDto);
        return Result.build(token,ResultCodeEnum.SUCCESS);

    }

    /**
     * 通过token 获取用户信息
     * @return
     */

    @GetMapping("/api/user/userInfo/auth/getCurrentUserInfo")
    public Result getCurrentUserInfo(HttpServletRequest request){
        // 获取token,请求头
        String token = request.getHeader("token");
        UserInfo currentUserInfo = userService.getCurrentUserInfo(token);
        return Result.build(currentUserInfo,ResultCodeEnum.SUCCESS);
    }

    @Autowired
    UserAddressService userAddressService;

    /**
     * api/user/userAddress/auth/findUserAddressList
     */

    @GetMapping("api/user/userAddress/auth/findUserAddressList")
    public Result findUserAddressList(HttpServletRequest request){

        String token = request.getHeader("token");
        Long userId = userService.getCurrentUserInfo(token).getId();

        List<UserAddress> userAddresses = userAddressService.findByUserId(userId);

        return Result.build(userAddresses,ResultCodeEnum.SUCCESS);


    }


    @GetMapping("/api/user/userAddress/findById/{id}")
    public UserAddress findById(@PathVariable("id") Long id){
        return userAddressService.findById(id);
    }




}
